let {promisify} = require('util');
let one = async function(num){
    return  new Promise((resolve, reject)=>{
        setTimeout(()=>{resolve(num)},num*1000)
    })
};
let all = async function(...args){
    console.log([...args]);
    return  new Promise((resolve , reject)=>{
        Promise.all([...args]).then((data)=>{
            resolve(data)
        })
    });
};
all(one(3),one(2),one(3));



let cache = null 
async function call_api(key) { // 如果同时有大量请求到来，在 getDataFromCache 还未返回结果时会发生缓存击穿，请编写代码来解决此问题 
     if (!cache) { 
         let data = await getDataFromCache(key) 
         cache = data 
     } 
     return cache 
}
let {promisify} = require('util');
let sleep = promisify(setTimeout());
const mapCache = function (){
    let map = new Map();
    return function f() {
        return map;
    }
}();
let map = mapCache();
// 这里可以redis来代替
// 这里一个API缓存的数据
async function getDataFromCache(key){
    let value = map.get(key);
    if(!value){
        mutex = new Date().getTime() + 1000*60; // 60s
        map.set(key, mutex); //设置锁
        value.data = await service.getDbData(); // 模拟获取数据库数据
        // 穿透
        if(!value.data){
            value.time = new Date().getTime() + 1000*60*(3*Math.random()+2); //2到5分钟
        }else{
            value.time = new Date().getTime() + 1000*60*(5*Math.random()+3); //3到8分钟
        }
        map.set(key, value);
        return value;
    }else{
        if(value.mutex){
            sleep(100); //休息100毫秒再试
           return getDataFromCache(key);
        }
        let time = value.time; // 过期时间
        let data = value.data; // 缓存数据
        if(time <= new Date().getTime()){
            map.set(key, null); //设置锁
            return getDataFromCache(key);
        }else{
            return data;
        }
    }
}
